package cn.green.core.front.model;

import cn.green.core.components.field.DefaultTypeCom;
import cn.green.core.components.store.field.DefaultValueTypeStore;
import cn.green.core.model.QField;
import com.alibaba.fastjson.JSONObject;
import cn.green.core.components.field.FieldCheckTypeCom;
import cn.green.core.components.store.field.FieldCheckTypeStore;
import lombok.Data;

import java.util.List;

/**
 * 输入组件
 */
@Data
public abstract class Input {

    public Input() {
    }

    public Input(QField field) {
        fieldName = field.getFieldName();
        this.titleName = field.getAliasName();
        List<String> fieldCheck = field.getFieldCheck();
        if (fieldCheck != null && !fieldCheck.isEmpty()) {
            for (String check : fieldCheck) {
                FieldCheckTypeCom fieldCheckTypeCom = FieldCheckTypeStore.get(check);
                if (fieldCheckTypeCom != null) {
                    if (fieldCheckTypeCom.required()) {
                        this.required = true;
                        break;
                    }
                }
            }
        }
        String defaultType = field.getDefaultType();
        if (defaultType != null && !defaultType.isEmpty()) {
            DefaultTypeCom defaultTypeCom = DefaultValueTypeStore.get(defaultType);
            Object object = defaultTypeCom.get(field);
            this.setDefaultValue(object);
        }
    }

    /**
     * 输入字段名称
     */
    protected String fieldName;

    /**
     * 输入标题名称
     */
    protected String titleName;

    /**
     * 该输入框的默认值
     */
    protected Object defaultValue;

    /**
     * 是否必填
     */
    protected boolean required;

    /**
     * 输入组件配置
     */
    protected JSONObject props;

    /**
     * 是否只读
     */
    protected boolean readOnly;

    /**
     * 输入值类型
     */
    public abstract String type();

    /**
     * 组件名称
     * @return
     */
    public abstract String widget();

    /**
     * 该组件转换成前端组件
     * @return
     */
    public abstract JSONObject extra();

    public JSONObject baseFront() {
        JSONObject front = new JSONObject();
        front.put("widget", this.widget());
        front.put("type", this.type());
        front.put("title", this.getTitleName());
        front.put("required", this.isRequired());
        front.put("readOnly", this.isReadOnly());
        front.put("default", this.getDefaultValue());
        return front;
    }

    public JSONObject toFront() {
        JSONObject front = this.baseFront();
        JSONObject extra = this.extra();
        if (extra != null) {
            front.putAll(extra);
        }
        return front;
    }
}
